<template>
  <div class="dingtalk-login-container">
    <div class="login-box">
      <h2>钉钉登录</h2>
      
      <div class="logo">
        <img src="https://gw.alipayobjects.com/zos/rmsportal/rQtOPqidJZFeibHxkowF.svg" alt="钉钉" />
      </div>
      
      <p class="description">使用钉钉账号快速登录</p>
      
      <button @click="loginWithDingtalk" class="dingtalk-btn">
        <svg t="1636974000000" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2582"><path d="M213.76 512 0 0l426.24 213.76 0.02 384L213.76 512zM810.24 213.76 597.76 0l0 384L810.24 170.666667 810.24 213.76zM810.24 810.24 597.76 1024l0-384 85.333333-43.946667L810.24 810.24z" p-id="2583"></path></svg>
        钉钉登录
      </button>
      
      <div class="other-login">
        <router-link to="/login">账号密码登录</router-link>
        <span>|</span>
        <router-link to="/login-code">验证码登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import router from '@/router'
import axios from 'axios'

// 钉钉配置
const DINGTALK_APP_KEY = 'dingsmy7vmfafwgedabz'

// 钉钉登录
const loginWithDingtalk = () => {
  // 构建回调URL
  const redirectUri = `${window.location.origin}/dingtalk-login`
  
  // 使用钉钉新版OAuth2授权接口
  // scope: openid 或 openid corpid (需要URL编码为 openid%20corpid)
  const scope = 'openid'  // 也可以使用 'openid corpid' 获取企业信息
  const state = Date.now().toString() // 防止CSRF攻击
  
  const authUrl = `https://login.dingtalk.com/oauth2/auth?client_id=${DINGTALK_APP_KEY}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${state}&prompt=consent`
  
  console.log('=== 跳转到钉钉授权页面 ===')
  console.log('授权URL:', authUrl)
  console.log('回调地址:', redirectUri)
  
  // 跳转到钉钉授权页面
  window.location.href = authUrl
}

// 检查是否是钉钉回调（处理从后端回调回来的token）
onMounted(() => {
  const urlParams = new URLSearchParams(window.location.search)
  // 钉钉可能返回code或authCode，优先使用code
  const code = urlParams.get('code') || urlParams.get('authCode')
  const access_token = urlParams.get('access_token')
  
  console.log('URL参数:', Object.fromEntries(urlParams))
  console.log('获取到的code:', code)
  
  // 如果是从钉钉授权页面回调回来的（有code）
  if (code) {
    handleDingtalkCallback(code)
  }
  // 如果是后端处理完回调后重定向回来的（有access_token）
  else if (access_token) {
    const user_id = urlParams.get('user_id')
    const username = urlParams.get('username')
    
    console.log('接收后端回调的token')
    
    // 保存用户信息
    localStorage.setItem('token', access_token)
    localStorage.setItem('user_id', user_id)
    localStorage.setItem('username', username)
    
    // 跳转到主页面
    router.push('/feed')
  }
})

// 处理钉钉回调（如果直接从前端调用）
const handleDingtalkCallback = async (code) => {
  try {
    console.log('===== 钉钉登录流程开始 =====')
    console.log('收到的 code:', code)
    console.log('完整URL:', window.location.href)
    
    // 检查 code 是否有效
    if (!code || code.length < 10) {
      console.error('❌ Code无效或已过期')
      console.error('Code值:', code)
      alert('登录失败：授权码无效。请确保已从钉钉授权页面返回')
      router.push('/login')
      return
    }
    
    // 调用后端接口
    console.log('准备发送code到后端...')
    const response = await axios.post('/api/auth/login-by-dingtalk', {
      code: code
    })
    
    console.log('✅ 钉钉登录响应:', response.data)
    
    // 验证 token 是否存在
    const access_token = response.data?.access_token
    if (!access_token) {
      console.error('❌ 登录响应中没有 access_token')
      console.error('完整响应:', JSON.stringify(response.data, null, 2))
      alert('登录失败：未收到有效token')
      return
    }
    
    console.log('Token to save:', access_token.substring(0, 30) + '...')
    console.log('Token length:', access_token.length)
    
    // 保存用户信息
    localStorage.setItem('token', access_token)
    localStorage.setItem('user_id', response.data.user_id)
    localStorage.setItem('username', response.data.username)
    
    // 验证保存是否成功
    const savedToken = localStorage.getItem('token')
    console.log('验证保存 - Token exists:', !!savedToken)
    console.log('验证保存 - Token value:', savedToken ? savedToken.substring(0, 30) + '...' : 'NULL')
    console.log('验证保存 - Token length:', savedToken?.length)
    
    if (savedToken !== access_token) {
      console.error('❌ Token保存失败！期望值:', access_token.substring(0, 30))
      console.error('实际保存值:', savedToken)
      alert('警告：Token可能未正确保存')
    }
    
    console.log('✅ 用户信息已保存')
    console.log('===== 钉钉登录成功 =====')
    
    // 跳转到主页面
    router.push('/feed')
  } catch (error) {
    console.error('===== 钉钉登录失败 =====')
    console.error('错误对象:', error)
    console.error('错误响应:', error.response)
    console.error('错误状态码:', error.response?.status)
    console.error('错误数据:', error.response?.data)
    
    // 显示详细错误信息
    const errorMsg = error.response?.data?.detail || error.message || '未知错误'
    console.error('最终错误消息:', errorMsg)
    
    // 更友好的错误提示
    let userFriendlyMsg = errorMsg
    
    if (error.response?.status === 500) {
      userFriendlyMsg = '服务器内部错误。请确保后端服务已重启，并查看后端控制台的详细错误日志。'
    } else if (error.response?.status === 401) {
      userFriendlyMsg = errorMsg
    } else if (error.response?.status === 404) {
      userFriendlyMsg = '接口不存在。请检查后端路由配置。'
    }
    
    alert(userFriendlyMsg)
    console.error('\n请查看后端控制台的日志以获取更详细的错误信息')
    router.push('/login')
  }
}
</script>

<style scoped>
.dingtalk-login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 400px;
  width: 100%;
  text-align: center;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}

.logo {
  margin: 30px 0;
}

.logo img {
  width: 80px;
  height: 80px;
}

.description {
  color: #666;
  margin-bottom: 30px;
  font-size: 14px;
}

.dingtalk-btn {
  width: 100%;
  padding: 14px 20px;
  background-color: #1677FF;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  transition: background-color 0.3s;
}

.dingtalk-btn:hover {
  background-color: #0958d9;
}

.dingtalk-btn .icon {
  width: 20px;
  height: 20px;
  fill: white;
}

.other-login {
  margin-top: 30px;
  font-size: 14px;
  color: #666;
}

.other-login a {
  color: #1677FF;
  text-decoration: none;
  margin: 0 10px;
}

.other-login a:hover {
  text-decoration: underline;
}

.other-login span {
  color: #ddd;
}
</style>